package com.sprite.framework.entity.script;

import java.util.HashMap;
import java.util.Map;

import com.sprite.framework.entity.DataScriptStatement;
import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.EntityScript;
import com.sprite.framework.entity.model.ModelEntity;
import com.sprite.framework.entity.model.ModelEntityUtil;
import com.sprite.framework.entity.model.ModelEntityView;
import com.sprite.utils.UtilString;

/**
 * 插入脚本
 * @author Jack
 *
 */
public final class EntityInsertScript implements EntityScript{
	

	private String entityName;
	
	/**
	 * field collection
	 */
	private Map<String, Object> fieldsToUpdate = new HashMap<String, Object>();

	// 生成的key
	private Map<String, Object> generatedKey = new HashMap<>();
	
	public EntityInsertScript(String entityName) {
		this.entityName = entityName;
	}

	protected EntityInsertScript() {
		
	}
	
	public void makeStatement(DataScriptStatement statement, ModelEntityView modelViewEntity) throws EntityException{
		initModelViewEntity(modelViewEntity);
		
		ModelEntity modelEntity = ModelEntityUtil.getModelEntity(entityName);
		
		statement.append(UtilString.place("INSERT INTO {}(", modelEntity.getTableName()));
		
		int lg = fieldsToUpdate.size();
		for(Map.Entry<String, Object> entry : fieldsToUpdate.entrySet()) {
			statement.addParam(entry.getValue());
			statement.append(modelEntity.getModelField(entry.getKey()).getColName());
			if(lg > 1) {
				statement.append(",");
			}else {
				statement.append(")");
			}
			lg--;
		}
		
		statement.append(" VALUES(");
		lg = fieldsToUpdate.size();
		while(lg>0) {
			if(lg > 1) {
				statement.append("?,");
			}else {
				statement.append("?)");
			}
			lg--;
		}
	}

	public void addFields(Map<String, Object> fields) {
		fieldsToUpdate.putAll(fields);
	}
	
	private void initModelViewEntity(ModelEntityView modelViewEntity) throws EntityException{
		if(modelViewEntity == null){
			return ;
		}
	}

	public Map<String, Object> getGeneratedKey() {
		return generatedKey;
	}
	
	public void addGeneratedKey(String prop, Object value) {
		generatedKey.put(prop, value);
	}

	public String getEntityName() {
		return entityName;
	}

	@Override
	public DataScriptStatement getStatement() {
		DataScriptStatement statement = new DataScriptStatement();
		makeStatement(statement, null);
		return statement;
	}

}
